<template>
  <div class="camera-box" style="width: 850px;">
    <div style="text-align: center;font-size: 14px;font-weight: bold;margin-bottom: 10px;">3秒后将进行拍照，请正视摄像头</div>
    <!-- 这里就是摄像头显示的画面 -->
    <video id="video" width="400" height="300" style="margin: auto; display: block"></video>
    <canvas id='canvas' width='400' height='300' style="display: none"></canvas>
  </div>
</template>
<script>

import {putImgLogin} from "@/api/ai-face";

export default {
  name: "FaceLogin",
  props:{
    tackPhoto:{//父组件传过来的状态
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      loadingbut:false,
      preViewVisible: false,
      blobFile: null,
      canvas: null,
      video: null,
      mediaStreamTrack: '',
    }
  },
  watch:{
    tackPhoto:{
      immediate: true,
      handler (newVal) {//监听接收到拍摄状态后，开始调取摄像头权限。如果功能是在一个组件里面，下面步骤可以直接写在自己的触发方法里面
        if (newVal) {
          let video = document.querySelector('video');
          let text = document.getElementById('text');
          // var mediaStreamTrack;

          // 兼容代码
          window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);

          if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
          }
          if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function(constraints) {
              var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
              if (!getUserMedia) {
                return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
              }
              return new Promise(function(resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
              });
            }
          }

          //摄像头调用配置
          let mediaOpts = {
            audio: false,
            video: { facingMode: "environment"} // 或者 "user"
            // video: { width: 1280, height: 720 }
            // video: { facingMode: { exact: "environment" } }// 或者 "user"
          }

          let that=this;
          navigator.mediaDevices.getUserMedia(mediaOpts).then(function(stream) {
            that.mediaStreamTrack = stream;
            video = document.querySelector('video');
            if ("srcObject" in video) {
              video.srcObject = stream
            } else {
              video.src = window.URL && window.URL.createObjectURL(stream) || stream
            }
            video.play();
          }).catch(function (err) {
            console.log(err)
          });

        }
      },
      deep:true
    },
  },
  mounted() {
    // 摄像头
    this.video = document.getElementById('video')
    //画布
    this.canvas = document.getElementById('canvas')

    this.delayTakePhone()
  },
  methods: {
    delayTakePhone() {//点击拍照截图画面
      let that = this;
      setTimeout(() => {
        that.canvas.getContext('2d').drawImage(this.video, 0, 0, 400, 300);
        that.blobFile = that.canvas.toDataURL('image/jpeg');
        that.preViewVisible = true;

        let formData = new FormData()
        formData.append('file', this.blobFile);//图片内容
        // console.log(that.blobFile)
        // 上传图片
        putImgLogin(formData).then(response=>{//后台接口
          this.loadingbut=false
          this.$emit('closeDialog') // 触发自定义事件，名称为'closeDialog'，告知父组件关闭对话框
          this.tackPhoto=false
          this.canvas.getContext('2d').clearRect(0, 0, 400, 300);//清除画布
          let userInfo = response.data.userInfo
          if (userInfo === undefined){
            alert("请录入人脸信息！！！")
          }else {
            alert("你好，" + userInfo)
          }
          this.closeCamera()
        },error=>{
          this.loadingbut=false;
          window.console.log(error);
        });
      }, 3000);
    },
    closeCamera(){
      this.mediaStreamTrack.getVideoTracks().forEach(function (track) {
        track.stop();
      });
    }
  }
}
</script>
<style>
.camera-box #canvas{
  border: 1px solid #DCDFE6;
}
</style>
